﻿//using Newtonsoft.Json.Linq;

namespace KingerRobot.MexicoSailunMDC.Biz;
/// <summary>
/// 二次线体扫描仪（入库前） 3号/4号 插入扫码记录
/// </summary>
/// //{"LineScannerName":"3号二次条码扫描","LineScannerId":10010401,"LineScannerLoc":20010401,"StationNo":"k10"}
public class LineScannerBiz : K8.MDCBB.Biz
{
    private const string ClassName = nameof(LineScannerBiz);

    #region 配置参数
    private ParamData Param { get; set; }

    class ParamData
    {
        /// <summary>
        /// 扫描仪设备ID
        /// </summary>
        public long LineScannerId { get; set; }
        /// <summary>
        /// 扫描仪位置ID
        /// </summary>
        public long LineScannerLoc { get; set; }
        /// <summary>
        /// 线体编号
        /// </summary>
        public string StationNo { get; set; }
        /// <summary>
        /// 扫描仪名称
        /// </summary>
        public string LineScannerName { get; set; }
    }
    #endregion

    #region PLC 通讯参数
    private ValueData Data { get; set; }
    class ValueData
    {
        /// <summary>
        /// 产品条码
        /// </summary>
        public string ProductCode { get; set; }

        /// <summary>
        /// 0:PLC读取后可改成 0
        /// 1:WCS任务下传完成..............可读可写/WCS读取到 0，下发任务，PLC接收到 1，改为 0。
        /// </summary>
        public int TaskFlag { get; set; }

        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }
        /// <summary>
        /// 读取任务号（上段线体任务读取后【有值】）才下传新任务
        /// </summary>
        public int WorkNo { get; set; }
        /// <summary>
        /// 是否读取条码
        /// </summary>
        public int IsRead { get; set; } = 1;
    }
    #endregion

    #region 缓存
    private CacheData Cache { get; set; }
    class CacheData
    {
        /// <summary>
        /// 计数
        /// </summary>
        public long TireCount { get; set; }
        /// <summary>
        /// 条码
        /// </summary>
        public string ProductCode { get; set; }
        /// <summary>
        /// 扫描条码 更新后以此为准
        /// </summary>
        //public string ScannerProduct { get; set; }
    }
    #endregion

    #region 实时日志
    private StepData Step { get; set; }
    class StepData
    {
        private string _msg = string.Empty;
        public string StepMsg
        {
            get
            {
                return this._msg;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this._msg = string.Empty;
                    return;
                }
                this._msg = $"{ClassName}|{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}>>{value}";
            }
        }
    }
    private void StepMsg(string msg)
    {
        this.Step.StepMsg = msg;
        WriteLog(msg);
    }
    #endregion

    #region 文件日志（运行需要 Nlog 配置）
    private void WriteLog(string message)
    {
        K8.LSF.Client.Log(new K8.LSF.Log { Data = message });
    }
    #endregion 

    /// <summary>
    /// 和 PLC 通讯对象
    /// </summary>
    private BizData BizData { get; set; }
    public int Execute(BizData writer)
    {
        return 0;
        // Excute 方法外使用 BizData
        //this.BizData = writer;
        //// 返回参数
        //var result = 0;
        //this.StepMsg($"扫描{Value.ProductCode}——开始");

        //// 获取条码
        //var productCode = Value.ProductCode;
        //// 条码为空
        //if (string.IsNullOrWhiteSpace(productCode) || productCode.StartsWith(ConstFields.Default))
        //{
        //    this.StepMsg($"条码为空, 扫描仪{Param.LineScannerId}-{Param.LineScannerLoc}-{Param.LineScannerName} | 线体编号:{Param.StationNo},线体任务:{Value.WorkNo}");
        //    return result;
        //}

        //if (productCode.StartsWith(ConstFields.NoRead)&& Param.LineScannerId== (int)EnumScannerLoc.Four)
        //{
        //    this.StepMsg($"Noread在二次扫描位置禁止创建任务, 扫描仪{Param.LineScannerId}-{Param.LineScannerLoc}-{Param.LineScannerName} | 线体编号:{Param.StationNo},线体任务:{Value.WorkNo}");
        //    return result;
        //}

        //this.StepMsg($"扫描{productCode}——LineScanner记录条码,缓存计数{Cache.TireCount},扫描计数{Value.TireCount}");

        ////246976 二次扫描修改任务,扫描仪为20010401,重选堆垛机货位为20052402

        ////// 创建扫码记录
        //if (Cache.ProductCode != this.Value.ProductCode)
        //{

        //    //var taskService = K8.RSF.Client.Create<ITaskService>();
        //    //taskService.GetTaskBeanByProductCode(productCode);
        //    //taskService.BakAndDeleteCmd()

        //    var scannerService = K8.RSF.Client.Create<IScannerService>();
        //    var scannerResult = scannerService.AddWcsScannerSec(Param.LineScannerLoc, productCode, "通过扫描口添加", 0);
        //    if (scannerResult > 0)
        //    {
        //        Cache.ProductCode = this.Value.ProductCode;
        //    }
        //}



        //return result;
    }

    private int SetTaskInfo(BizTaskBean task)
    {
        var sProductCode = task.ProductCode;
        //var code = sProductCode?.Chunk(2).ToList();

        return this.BizData.WriteData(new
        {
            Destination = task.TargetPlcLoc,        // 目标地址
            WorkNo = task.TaskNo,                   // 流水号
            OutSize = task.OutSize,                 // 外径
            SProductCode = sProductCode,
            //SProductCode01 = GetProductItem(code, 1),
            //SProductCode02 = GetProductItem(code, 2),
            //SProductCode03 = GetProductItem(code, 3),
            //SProductCode04 = GetProductItem(code, 4),
            //SProductCode05 = GetProductItem(code, 5),

            //Start = task.StartCmdPlcLoc,            // 开始地址
            //CoupledNo = task.TaskGroup,             // 组
            //CoupledWorkNo = task.TaskGroupIndex,    // 顺序号
            //Height = task.Height,                   // 高
        });
    }
    /// <summary>
    /// 获取拆分条码
    /// </summary>
    /// <param name="codes"></param>
    /// <param name="ind">从1开始</param>
    /// <returns></returns>
    private string GetProductItem(List<char[]> codes, int ind)
    {
        if (codes.Count >= ind)
        {
            return new string(codes[ind - 1]);
        }
        return string.Empty;
    }
    private int SetTaskFlag()
    {
        var mark = this.BizData.WriteData(new
        {
            TaskFlag = EnumLineAck.WCSDownFinish,
        });
        Thread.Sleep(100);
        return mark;
    }
}
